﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using AutoMapper;
using OnlineEducation.Constants;
using OnlineEducation.Controllers;
using OnlineEducation.Data;
using OnlineEducation.Helpers;
using OnlineEducation.Models.JQueryTable;
using OnlineEducation.Models.ServerAPIModels;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;

namespace OnlineEducation.Areas.MeetingRoom.Controllers
{
    [Area("Classroom")]
    [Route("[controller]/[action]")]
    [Authorize(Roles = "SuperAdmin")]
    public class ClassroomController : BaseController
    {
        private readonly ApplicationDbContext _context;
        private readonly ILogger _logger;
        private readonly IMapper _mapper;
        private readonly IConfiguration _configuration;
        public ClassroomController(ApplicationDbContext context, ILogger<ClassroomController> logger, IMapper mapper, IConfiguration configuration)
        {
            _context = context;
            _logger = logger;
            _mapper = mapper;
            _configuration = configuration;
        }
        // GET: ClassroomController
        public ActionResult Index()
        {
            return View();
        }

        [HttpPost]
        public IActionResult GetAll(DTParameters param)
        {
            var get_meeting_param = Utility.CreateParams(ServerAPI.GetMeetings);

            var server_address = _configuration.GetSection("BBB_Server_Address").Value;

            var response = HttpHelper.HttpsGet($"{server_address}/bigbluebutton/api/getMeetings?" + get_meeting_param);

            var ret = Utility.XMLToModel<GetMeetingsResponseEntity>(response);

            var count = ret.meetings.Count();

            return Json(new
            {
                draw = param.Draw,
                data = ret.meetings.OrderByDescending(n => n.createDate).Skip(param.Start).Take(param.Length).ToArray(),
                recordsFiltered = count,
                recordsTotal = count
            });

        }


        // GET: ClassroomController/Add
        [HttpGet]
        public ActionResult Add()
        {
            return View();
        }

        // POST: ClassroomController/Add
        [HttpPost]
        //[ValidateAntiForgeryToken]
        public ActionResult Add([FromBody] CreateMeeting data)
        {
            if (!ModelState.IsValid)
            {
                return BadRequest(ModelState);
            }
            try
            {
                //data.meetingID = Guid.NewGuid().ToString();

                data.logoutURL = "http://onlineeducation.futureinfo.cn";

                var param = Utility.CreateParams<CreateMeeting>(data, ServerAPI.Create);

                var server_address = _configuration.GetSection("BBB_Server_Address").Value;

                var httprequest = HttpHelper.HttpsGet($"{server_address}/bigbluebutton/api/create?" + param);

                var response = Utility.XMLToModel<CreateResponseEntity>(httprequest);

                if (response.returncode != "SUCCESS")
                {
                    return Json(new { success = false, message = response.message });
                }

                return Json(new { success = true, message = "教室新建成功." });

            }
            catch (Exception ex)
            {
                return Json(new { success = false, message = ex.Message });
            }
        }

        [HttpGet]
        public IActionResult Join(string meetingid, string pwd)
        {
            var server_address = _configuration.GetSection("BBB_Server_Address").Value;

            var joinmeeting = new JoinMeeting
            {
                fullName = "管理员",
                meetingID = meetingid,
                password = pwd,
                userID = "管理员" + new Random(10).Next().ToString(),
                redirect = "true", // 直接返回了html页面， 在为false的时候，返回xml结果，包含会议地址
                joinViaHtml5 = "true",
                
            };

            var param = Utility.CreateParams<JoinMeeting>(joinmeeting, ServerAPI.Join);

            return Json(new
            {
                success = true,
                ps = param,
                clientURL = $"{server_address}/"
            });
        }

        public IActionResult End(string meetingid, string pwd)
        {
            var server_address = _configuration.GetSection("BBB_Server_Address").Value;

            var endMeeting = new EndMeeting
            {
                meetingID = meetingid,
                password = pwd,
            };

            var param = Utility.CreateParams<EndMeeting>(endMeeting, ServerAPI.End);

            var httprequest = HttpHelper.HttpsGet($"{server_address}/bigbluebutton/api/end?" + param);

            var response = Utility.XMLToModel<CreateResponseEntity>(httprequest);

            if (response.returncode != "SUCCESS")
            {
                return Json(new { success = false, message = response.message });
            }

            return Json(new
            {
                success = true,
                message = response.message

            });
        }
    }
}
